<template>
  <section class="py-12 bg-neutral min-h-screen">
    <div class="container mx-auto px-4">
      <!-- 页面标题 -->
      <div class="text-center mb-10">
        <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4">我的作品</h2>
        <p class="text-gray-600 max-w-2xl mx-auto">管理和查看你创建的所有漫画作品</p>
      </div>
      
      <!-- 未登录状态 -->
      <div v-if="!isLoggedIn" class="text-center py-20 bg-white rounded-xl shadow-sm">
        <svg class="w-20 h-20 text-gray-300 mx-auto mb-4" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M16 21V19C16 17.9391 15.5786 16.9217 14.8284 16.1716C14.0783 15.4214 13.0609 15 12 15C10.9391 15 9.92172 15.4214 9.17157 16.1716C8.42143 16.9217 8 17.9391 8 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M12 11C14.2091 11 16 9.20914 16 7C16 4.79086 14.2091 3 12 3C9.79086 3 8 4.79086 8 7C8 9.20914 9.79086 11 12 11Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <h3 class="text-xl font-medium text-gray-500 mb-2">您目前尚未登录</h3>
        <p class="text-gray-400 mb-8">登录后可以查看和管理您的作品</p>
        <button 
          class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
          @click="$router.push('/login')"
        >
          <i class="fa fa-sign-in mr-2"></i>登录账户
        </button>
      </div>
      
      <!-- 已登录状态 -->
      <div v-else>
        <!-- 作品状态筛选 -->
        <div class="flex flex-wrap justify-center gap-3 mb-8">
          <button 
            @click="setFilter('all')"
            :class="activeFilter === 'all' ? 'bg-primary text-white' : 'bg-white hover:bg-gray-100'"
            class="px-4 py-2 rounded-lg transition-colors"
          >全部作品</button>
          <button 
            @click="setFilter('completed')"
            :class="activeFilter === 'completed' ? 'bg-primary text-white' : 'bg-white hover:bg-gray-100'"
            class="px-4 py-2 rounded-lg transition-colors"
          >已完成</button>
          <button 
            @click="setFilter('draft')"
            :class="activeFilter === 'draft' ? 'bg-primary text-white' : 'bg-white hover:bg-gray-100'"
            class="px-4 py-2 rounded-lg transition-colors"
          >草稿</button>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-16 bg-white rounded-xl shadow-sm">
          <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent mb-4"></div>
          <p class="text-gray-500">加载中...</p>
        </div>
        
        <!-- 作品列表 -->
        <div v-else-if="works.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <WorkCard 
            v-for="work in filteredWorks" 
            :key="work.id"
            :work="work"
            @work-deleted="handleWorkDeleted"
          />
        </div>
        
        <!-- 空状态 -->
        <div v-else class="text-center py-16 bg-white rounded-xl shadow-sm">
          <svg class="w-20 h-20 text-gray-300 mx-auto mb-4" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M4 19.5C4 18.837 4.26339 18.2011 4.73223 17.7322C5.20107 17.2634 5.83696 17 6.5 17H20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M6.5 2H20V22H6.5C5.83696 22 5.20107 21.7366 4.73223 21.2678C4.26339 20.7989 4 20.163 4 19.5V4.5C4 3.83696 4.26339 3.20107 4.73223 2.73223C5.20107 2.26339 5.83696 2 6.5 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <h3 class="text-lg font-medium text-gray-500 mb-2">你还没有任何作品</h3>
          <p class="text-gray-400 mb-6">快去创建你的第一个漫画作品吧</p>
          <button 
            class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
            @click="$router.push('/')"
          >
            <i class="fa fa-plus mr-2"></i>创建新作品
          </button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { get } from '../utils/api.js'
import WorkCard from '../components/WorkCard.vue'

// 响应式数据
const works = ref([])
const activeFilter = ref('all')
const loading = ref(false)
const isLoggedIn = ref(false)
console.log(works.value);

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = localStorage.getItem('userInfo')
  const authToken = localStorage.getItem('authToken')
  isLoggedIn.value = !!userInfo && !!authToken
}

// 设置筛选条件
const setFilter = (filter) => {
  activeFilter.value = filter
}

// 根据筛选条件过滤作品
const filteredWorks = computed(() => {
  if (activeFilter.value === 'all') return works.value
  return works.value.filter(work => work.status === activeFilter.value)
})

// 从后端获取作品列表
const fetchWorks = async () => {
  try {
    loading.value = true
    // 向后端API发送请求时传递分页参数
    const response = await get('/generate/list', { 
      params: { 
        offset: 0, 
        limit: 5 
      } 
    })
    
    // 检查响应状态
    if (response.data && Array.isArray(response.data)) {
      // 将原始作品数据存储到window对象中，供WorkDetail.vue使用
      window.allWorks = response.data;
      
      // 转换API返回的数据格式为组件需要的格式
      works.value = response.data.map((item, index) => {
        // 安全地获取文本内容，确保它是字符串类型
        const textContent = item.Text || item.text || '';
        // 计算标题，避免对undefined或null调用substring
        const safeTitle = textContent && typeof textContent === 'string' 
          ? textContent.substring(0, 10) + '...' 
          : '作品 ' + (index + 1);
        
        // 从Draws数组获取第一个图片URL作为封面，彻底清理所有可能的格式问题
        const firstDraw = item.Draws && Array.isArray(item.Draws) && item.Draws.length > 0 ? item.Draws[0] : null;
        const coverUrl = firstDraw && firstDraw.Url && typeof firstDraw.Url === 'string'
          ? firstDraw.Url.replace(/[`"']/g, '').replace(/\s+/g, '').trim()
          : '/vite.svg';
        
        return {
          id: item.Uid || index + 1, // 保持现有id字段
          Id: String(item.Id), // 直接将Id转换为字符串，避免JavaScript大整数精度问题
          title: safeTitle,
          cover: coverUrl, // 使用Draws数组中的第一张图片作为封面
          created: item.Ctime ? new Date(item.Ctime * 1000).toISOString().split('T')[0] : new Date().toISOString().split('T')[0], // 使用服务器返回的时间戳
          status: 'completed', // 默认设置为已完成状态
          style: item.Style || '未知风格', // 使用大写Style字段
          tone: item.Tone || '未知基调', // 使用大写Tone字段
          originalData: item // 保存原始数据，方便后续使用
        };
      });
    } else {
      console.error('获取作品列表失败:', response.msg || '未知错误')
      works.value = []
    }
  } catch (error) {
    console.error('请求作品列表时发生错误:', error)
    works.value = []
  } finally {
    loading.value = false
  }
}

// 处理作品删除事件
const handleWorkDeleted = (deletedWorkId) => {
  console.log(deletedWorkId);
  
  // 从本地作品列表中移除已删除的作品，使用字符串比较以避免精度问题
  works.value = works.value.filter(work => String(work.Id) !== String(deletedWorkId))
  
  // 同时从window.allWorks中也移除，保持数据一致性
  if (window.allWorks && Array.isArray(window.allWorks)) {
    window.allWorks = window.allWorks.filter(item => 
      String(item.Id) !== String(deletedWorkId)
    )
  }
  
  // 重新获取作品列表以确保数据最新
  fetchWorks()
}

// 组件挂载时执行
onMounted(() => {
  checkLoginStatus()
  if (isLoggedIn.value) {
    fetchWorks()
  }
})
</script>